package cn.zl.common.manage.dashboard;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import oshi.SystemInfo;

import java.util.PriorityQueue;

public class MemoryDashboard extends BaseDashboard {

    private long total;
    private long used;
    private long available;
    private final PriorityQueue<MemoryRate> rateList = new PriorityQueue<>(NUM);

    public MemoryDashboard(SystemInfo si) {
        super(si);
    }

    public void addRate(String time, int rate) {
        if(rateList.size()>= NUM ){
            rateList.poll();
        }
        MemoryRate memoryRate = new MemoryRate();
        memoryRate.time = time;
        memoryRate.rate = rate;
        rateList.add(memoryRate);
    }

    @Override
    public JSONObject encode() {
        JSONObject json = new JSONObject();
        json.put("total", convert(total));
        json.put("used", convert(used));
        json.put("available", convert(available));
        final JSONArray rateList = new JSONArray();
        this.rateList.forEach(rate -> rateList.add(rate.encode()));
        json.put("rate_list", rateList);
        return json;
    }

    public static class MemoryRate implements BaseDashboard.IRate, Comparable<MemoryRate> {
        public String time;
        public int rate;

        @Override
        public JSONObject encode() {
            JSONObject json = new JSONObject();
            json.put("time", time);
            json.put("rate", rate);
            return json;
        }

        @Override
        public int compareTo(MemoryRate o) {
            return this.time.compareTo(o.time);
        }
    }

    public long getTotal() {
        return total;
    }

    public void setTotal(long total) {
        this.total = total;
    }

    public long getUsed() {
        return used;
    }

    public void setUsed(long used) {
        this.used = used;
    }

    public long getAvailable() {
        return available;
    }

    public void setAvailable(long available) {
        this.available = available;
    }
}
